package com.atguigu.java;

/**
 * 使用同步方法解决实现Runnable接口的线程安全问题
 *
 * 1.是实现类就不需要static
 */
class Window3 implements Runnable {

    private int ticket = 100;
    private static Object obj = new Object();

    @Override
    public  void run() {
        while (true) {
            show();
        }
    }


    //使用同步方法来实现锁的功能
    public synchronized void show() {//同步监视器：this
        if (ticket > 0) {

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println(Thread.currentThread().getName() + "买票，票号为：" + ticket);
            ticket--;
        }

    }
}


public class WindowTest3 {
    public static void main(String[] args) {
        Window3 window = new Window3();

        Thread w = new Thread(window);
        w.setName("窗口一：");
        Thread w2 = new Thread(window);
        w2.setName("窗口二：");
        Thread w3 = new Thread(window);
        w3.setName("窗口三：");

        w.start();
        w2.start();
        w3.start();
    }
}

